<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Log;

class UserOrder extends Model
{
    protected $table = 'user_order';
    public $timestamps = false;

    public function getCreateTimeAttribute($value)
    {
        return date('Y-m-d H:i:s', $value);
    }
    public function getProfitTimeAttribute($value)
    {
        return date('Y-m-d H:i:s', $value);
    }

    // 购买节点
    public function buyNode($user_id, $buy_num,$coin_num,$price, $service)
    {
        $buystatus = self::getTodayBuyNodeNum($user_id);
        if ($buystatus){
            if (self::getLang() == 'en') {
                throw new \Exception('You have purchased, please do not repeat the purchase');
            }
            throw new \Exception('您已购买，请勿重复购买');
        }
        
        $node = new self();
        $node->user_id = $user_id;
        $node->sid = $service['id'];
        $node->name = $service['name'];
        $node->days = $service['days'];
        $node->num = $buy_num;
        $node->coin_num = $coin_num;
        $node->total_release_times = $service['release_times'];
        $node->has_release_times = 0;
        $node->profit = $service['profit'];
        $node->create_time = time();
        $node->profit_time = 0;
        $node->status = 1;
        $node->price = $price;
        $node->save();

        return true;
    }

    // 已购买节点数量
    public function getBuyNodeNum($user_id)
    {
        return (int) self::where('user_id', $user_id)->count();
    }
    // 已购买节点数量
    public function getTodayBuyNodeNum($user_id)
    {
        $today = strtotime(date('Y-m-d'));

        return (int) self::where('user_id', $user_id)->where('create_time', '>=', $today)->where('status',1)->count();
    }

    // 每日产币
    public function mint()
    {
        self::query()->where("status",1)->orderBy('id', 'asc')->chunk(100, function ($nodes){ 
            foreach ($nodes as $node) { 
                if($node['total_release_times'] <= $node['has_release_times']){
                    continue;
                }
                $profit = round($node['profit'], 6);
                
                $childrens = UserInvite::where('up_user_id', $node->user_id)
                    ->where("rebate_status",1)
                    ->get(['id', 'rebate']);

                if(count($childrens) > 0){
                    foreach ($childrens as $children) {
                        $rebate = $children->rebate;
                        $leftprofit = round($profit - $rebate,2);
                        // 返佣记录
                        if($rebate > 0){
                            $log = new UserOrderLog();
                            $log->user_id = $children->user_id;
                            $log->order_id = $node->id;
                            $log->num = $rebate;
                            $log->type = 2; //类型:1周分 2返佣
                            $log->create_time = time();
                            $log->save();

                            Wallet::incrementUsdt($children->user_id, round($rebate,$node->price),2,1,'buy_service');
                        }
                        // 周分记录
                        if($leftprofit > 0){
                            $log = new UserOrderLog();
                            $log->user_id = $node->user_id;
                            $log->order_id = $node->id;
                            $log->num = $leftprofit;
                            $log->type = 1; //类型:1周分 2返佣
                            $log->create_time = time();
                            $log->save();

                            Wallet::incrementUsdt($node->user_id, round($leftprofit,$node->price),2,1,'buy_service');
                        }
                        Log::info('节点ID:'.$node->id.' 产币:'.$profit.' 返佣:'.$rebate.' 周分:'.$leftprofit);
                    }
                }else{
                    $log = new UserOrderLog();
                    $log->user_id = $node->user_id;
                    $log->order_id = $node->id;
                    $log->num = $profit;
                    $log->type = 1; //类型:1周分 2返佣
                    $log->create_time = time();
                    $log->save();

                    Wallet::incrementUsdt($node->user_id, round($profit,$node->price),2,1,'buy_service');
                }

                $node->daily_mint_num = $profit;
                $node->total_mint_num += $profit;
                $node->has_release_times += 1;
                $node->profit_time = time();

                // 完成
                if($node->has_release_times >= $node->total_release_times){
                    $node->status = 2;
                }
                $node->save();
            }
        });
    }

    /**
     * 节点名称
     *
     * @param  string  $value
     * @return string
     */
    public function getNameAttribute($value)
    {

        if (self::getLang() == 'en') {
            return sprintf('Node%s', $this->sn_id);
        }

        return $value;
    }

    public function getLang(){
        return request()->header('language');
    }
}
